

#include "unity.h"
#include "unity_fixture.h"

#include "Log.h"
#include "BSP.h"
#include "BSP_Sleep.h"
#include "IO.h"

#include "ICC/Etu_Timer.h"
#if 0
#include "gd32f30x_timer.h"

#define ETU_TIMER			TIMER5
#define ETU_TIMER_IRQn		TIMER5_IRQn
#define ETU_TIMER_CLK_ENABLE()  rcu_periph_clock_enable(RCU_TIMER5)
#define ETU_TIMER_CLK_FREQ()	(rcu_clock_freq_get(CK_APB1) * 2)

#define ETU_TIMER_CLEAR_COUNTOR()	timer_counter_value_config(ETU_TIMER, 0)
#define ETU_TIMER_SET_COUNTOR_PEAK(cnt) 	do{TIMER_CAR(ETU_TIMER) = (uint32_t)cnt;}while(0)
#define ETU_TIMER_GET_COUNTOR_PEAK() 		TIMER_CAR(ETU_TIMER)

volatile uint32_t etuTimerCountor;

void TIMER5_IRQHandler(void)
{
   timer_interrupt_flag_clear(ETU_TIMER, TIMER_INT_FLAG_UP);

   etuTimerCountor += 65536;
}


void ETUTimer_Setup(uint32_t freq){

	etuTimerCountor = 0;

	timer_parameter_struct timer_initpara;
	ETU_TIMER_CLK_ENABLE();
	timer_deinit(ETU_TIMER);
	uint32_t clk = ETU_TIMER_CLK_FREQ();
	
	/* TIMER1 configuration */
	timer_initpara.prescaler         = clk / freq - 1;
	timer_initpara.alignedmode       = TIMER_COUNTER_CENTER_UP;
	timer_initpara.counterdirection  = TIMER_COUNTER_UP;
	timer_initpara.period            = 0xFFFF;
	timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;
	timer_init(ETU_TIMER, &timer_initpara);
	
	timer_interrupt_flag_clear(ETU_TIMER, TIMER_INT_FLAG_UP);
	timer_interrupt_enable(ETU_TIMER, TIMER_INT_UP);
	nvic_irq_enable(ETU_TIMER_IRQn, 1, 0);

	timer_enable(ETU_TIMER);
}

uint32_t ETUTimer_GetCountor(void){
	uint32_t count;
	uint32_t hwCount;
	do{
		count = etuTimerCountor;
		hwCount = timer_counter_read(ETU_TIMER);
	}while(count != etuTimerCountor);

	return count + hwCount;
}

void ETUTimer_Delay(uint32_t clk){
	uint32_t c1 = ETUTimer_GetCountor();
	uint32_t c2;
	do{
		c2 = ETUTimer_GetCountor();
	}while((c2 - c1) < clk);
}
#endif 


TEST_GROUP(ETUTimer);


TEST_SETUP(ETUTimer)
{
	
}

TEST_TEAR_DOWN(ETUTimer)
{
}



TEST(ETUTimer, Calibration)
{
	static const IO_T led = {(void*)GPIOB, GPIO_PIN_1};
	IO_Init(&led, IO_Mode_OUT);
	ETUTimer_Init(4500000);
	uint32_t c1 = ETUTimer_GetCountor();
	BSP_Sleep_Ms(200);
	uint32_t c2 = ETUTimer_GetCountor();
	LOGD("clock", "%u", c2 - c1);
	while(1){
		IO_Set(&led, 1);
		ETUTimer_Delay(450000);
		IO_Set(&led, 0);
		ETUTimer_Delay(450000);
	}
}





